// 基础配置  http://192.168.235.238:7001
// 根据环境判断使用哪个域名  'https://ysdai.m3it.cn'; // 替想换为实际的API地址 https://ysdai.m3it.cn 

let url = 'https://ysdai.m3it.cn'
const accountInfo = wx.getAccountInfoSync()
var envVersion = accountInfo.miniProgram.envVersion
if(envVersion == 'develop'){
  url = 'http://127.0.0.1:7001'
}
if(envVersion == 'trial'){
 url = 'https://ysdai.m3it.cn';
}
if(envVersion == 'release'){
  url = 'https://ysdai.m3it.cn';
}


export const BASE_URL = url
const TIMEOUT = 6000000; // 请求超时时间，单位毫秒

// 请求拦截器
const requestInterceptor = (config) => {
  // 获取token
  const token = uni.getStorageSync('token');
  if (token) {
    config.header[ 'Authorization'] = token
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  
  // 请求成功
  if (statusCode >= 200 && statusCode < 300) {
    return data;
  }
  
  // 处理特定错误码
  switch (statusCode) {
    case 401:
      // token过期或未登录
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      // 跳转到登录页
      uni.navigateTo({
        url: '/pages/mine/login'
      });
      break;
    case 403:
      uni.showToast({
        title: '没有权限',
        icon: 'none'
      });
      break;
    case 404:
      uni.showToast({
        title: '请求的资源不存在',
        icon: 'none'
      });
      break;
    case 500:
      uni.showToast({
        title: '服务器错误',
        icon: 'none'
      });
      break;
    default:
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      });
  }
  
  return Promise.reject(response);
};

// 请求函数
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
	  // console.log( BASE_URL + options.url);
    // 合并配置
    const config = {
      url:  BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      timeout: TIMEOUT,
      ...options
    };
	
    // 请求拦截
    const interceptedConfig = requestInterceptor(config);

    // 显示加载提示
    if (!options.hideLoading) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
    }
	
	interceptedConfig.url = BASE_URL +interceptedConfig.url
	
    // 发起请求
    uni.request({
      ...interceptedConfig,
      success: (response) => {
        try {
          const result = responseInterceptor(response);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        reject(error);
      },
      complete: () => {
        // 隐藏加载提示
        if (!options.hideLoading) {
          uni.hideLoading();
        }
      }
    });
  });
};

// 封装常用请求方法
export const http = {
  get: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'GET',
      data,
      ...options
    });
  },
  
  post: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    });
  },
  
  put: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },
  
  delete: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  },

  // 上传文件
  upload: (url, filePath, formData = {}, options = {}) => {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: url.startsWith('http') ? url : BASE_URL + url,
        filePath,
        name: 'file',
        formData,
        header: {
          ...options.header
        },
        success: (response) => {
          try {
            const result = responseInterceptor(response);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
          reject(error);
        }
      });
    });
  }
};

export default request;
